// pages/index/decorcompany/livesite.js
var call = require("../../../utils/request.js")
var app = getApp()
var page = 0;
Page({
  data: {
    winHeight: "", //窗口高度
    currentTab: 0, //预设当前项的值  
    scrollLeft: 0, //tab标题的滚动条位置
    // tab切换
    toView: '',
    observer: true,
    observerParents: true,
    latitude: '',
    longitude: '',
    local: '',
    companyid: '',
    pages: 0,
    page: 1,
    polist:'',
    hidecode: true,
    showcode: false,
    cards: true,
    sid: '',
    card: '获取验证码',
    landing_page: '',
    basepeak: '',
    infotele: '',
    hidemap:false,
    showimg:true,
    state: false,
  },
  onLoad: function(options) {
    var that = this;
    var id = options.id
    wx.showLoading({ //显示toast
      title: '数据加载中...',
    });
    //请求数据
    wx.request({
      //url: 'http://5b7e5f5eadf2070014bfa349.mockapi.io/v4/livesite', 
      url: app.apiUrl("c=buildingsite/index&a=getlist"),
      data: {
        company_id: id,
        page_size:50
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: "GET",
      success: function(res) {
        console.log('请求成功', res.data)
        var polist = res.data.datas.list
        //console.log(polist)
        //console.log(polist.length)
       if (polist.length==0){
         that.setData({
           showempage:true,
           showitem:false
         })
       }else{
         var arr1 = []
         for (var i in polist) {
           var local = polist[i].location
           if (local == null) {
             local = '0,0'
             polist[i].state = false
           } else {
             local = polist[i].location
           }
           var strArray = local.split(",");
           arr1.push(strArray)
         }
         that.setData({
           polist: polist,
           local: arr1,
           companyid: id,
           showempage: false,
           showitem: true
         })
         setTimeout(function () {
           that.showmocker();
           that.distance()
         }, 100)
         setTimeout(function () {
           that.maps()
         }, 300)
       }  
      },
      fail: function(res) {
        console.log('请求失败', res.data)
      },
       complete: function () {
        wx.hideLoading(); //隐藏toast
      }
    })
    wx.getSystemInfo({
      success: function(res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR;
        //console.log(calc)
        that.setData({
          winHeight: calc
        });
      }
    });
    that.getlocal()
    call.getData('session', this.shuffleSuc, this.fail);
    setTimeout(function () {
      that.initcode()
    }, 200)
  },

  //获取session
  shuffleSuc: function (res) {
    //console.log(res)
    var that = this;
    var sid = res.data.PHPSESSID
    wx.setStorage({ //存储到本地
      key: "sid",
      data: sid
    })
    that.setData({
      sid: sid
    })
  },
  fail: function () {
    console.log("失败")
  },
  //初始获取验证码
  initcode: function () {
    var that = this
    var sid = that.data.sid
    var text = '获取验证码'
    wx.request({
      url: app.apiUrl("c=zhaobiao/index&a=view_visit	"),
      //url: 'http://www.newx.com/api/weixinapp/?c=zhaobiao/index&a=get_captcha',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': 'PHPSESSID=' + sid
      },
      method: 'GET',
      success: function (res) {
        //console.log(res.data)
        var code = res.data.datas.code
        var baskpage = res.data.datas.landing_page
        that.setData({
          card: code,
          hidecode: false,
          showcode: true,
          basepeak: baskpage
        })
        setTimeout(function () {
          that.setData({
            card: text,
          })
        }, 30000)
      }
    })
  },
  //初始化加载时地图下面的显示
  maps:function(){
    var that = this
    var polist = that.data.polist[0]
    if ((polist.distance == 12843) || (polist.distance == 12581) || (polist.distance == 12851)) {
      that.setData({
        state:false,
        distance: polist.distance,
        mapcount: polist
      })
    } else {
      that.setData({
        state: true,
        distance: polist.distance,
        mapcount: polist
      })
    }  
  },
  //获取当前位置
  getlocal: function() {
    var that = this
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        var latitude = res.latitude
        var longitude = res.longitude
        wx.setStorageSync('latitude', latitude)
        wx.setStorageSync('longitude', longitude)
        var speed = res.speed
        var accuracy = res.accuracy
        that.setData({
          latitude: latitude,
          longitude: longitude,
        })
      }
    })
  },
  //距离计算
  distance: function(e) {
    var that = this
    var la1 = wx.getStorageSync('latitude');
    var lo1 = wx.getStorageSync('longitude');
    var lati = that.data.latitude
    var longi = that.data.longitude
    if (!(la1 == lati) || !(lo1 == longi)) {
      that.getlocal();
    }
    // var postlists = that.data.polist
    var local = that.data.local
    var polist = that.data.polist
    var distance = []
    for (var i in local) {
      var La1 = la1 * Math.PI / 180.0;
      var La2 = local[i][1] * Math.PI / 180.0;
      var La3 = La1 - La2;
      var Lb3 = lo1 * Math.PI / 180.0 - local[i][0] * Math.PI / 180.0;
      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
      s = s * 6378.137; //地球半径
      s = parseInt(Math.round(s * 10000) / 10000);
      distance.push(s)
      //console.log(local[2][0])
      polist[i].distance = distance[i];
    }
    //console.log(polist)
    //隐藏掉经纬度为空的距离显示
    for(var i in polist){
      if ((polist[i].distance == 12843)|| (polist[i].distance == 12851)) {
        polist[i].state = false
      } else {
        polist[i].state = true
      }
    }
    that.setData({
      polist:polist
    })
  },

 //附近工地地图展示
  showmocker:function(e){
    var that = this
    var local = that.data.local
    var polist = that.data.polist
    var la1 = that.data.latitude
    var lo1 = that.data.longitude
    //console.log(polist)
    //console.log(local)
    var marker=[]
    for(var i=0;i<local.length;i++){
      if ((local[i][1] == 0) || (local[i][0] == 0)){
        var markers = ({
          id: i,
          latitude: 0,
          longitude: 0,
          iconPath: "../../../images/decormpany/mapker-icon.png",
          width: 0.5,
          height: 0.5,
          alpha: 1,
          callout: {
            content: '.',
            color: "#FFFFFF",
            fontSize: "1",
            borderRadius: "10",
            bgColor: "#008000",
            padding: 0,
            borderRadius: 5,
            display: "ALWAYS"
          },
        })
      }else{
        var markers = ({
          id: i,
          latitude: local[i][1],
          longitude: local[i][0],
          iconPath: "../../../images/decormpany/mapker-icon.png",
          width: 0.5,
          height: 0.5,
          alpha: 1,
          callout: {
            content: polist[i].schedule,
            color: "#FFFFFF",
            fontSize: "16",
            borderRadius: "10",
            bgColor: "#008000",
            padding: 5,
            borderRadius: 5,
            display: "ALWAYS"
          },
        })
      }
      marker.push(markers)
    }
    that.setData({
        markers:marker
    })
  },
  //地图标记点点击事件
  markertap:function(e){
    //console.log(e.markerId)
    var that = this
    var markers = that.data.markers
    //console.log(markers)
    var id = parseInt(e.markerId) 
    var polist = that.data.polist[id]
    for(var i in markers){
      markers[i].callout.bgColor = '#008000'
      markers[id].callout.bgColor = '#FF9000'
    }
    //console.log(id)
    //console.log(markers)
    if ((polist.distance == 12843) || (polist.distance == 12581)) {
      that.setData({
        state: false,
        distance: polist.distance,
        mapcount: polist,
        //markers: markers
      })
    } else {
      that.setData({
        state: true,
        distance: polist.distance,
        mapcount: polist,
        markers: markers
      })
    }  
  },
  footerTap: app.footerTap,
  // 滚动切换标签样式
  switchTab: function(e) {
    var index = e.detail.current
    if(index==0){
      // this.onReachBottom()
      this.setData({
        "disableScroll": false
      })
    }else{
      this.setData({
        "disableScroll": true
      })
    }
    this.setData({
      currentTab: e.detail.current
    });
    this.checkCor();
  },
  // 点击标题切换当前页时改变样式
  // swichNav: function (e) {
  //var cur = e.target.dataset.current;
  //   if (this.data.currentTaB == cur) { return false; }
  //   else {
  //     this.setData({
  //       currentTab: cur
  //     })
  //   }
  // },
  //判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function() {
    var that = this
    if (that.data.currentTab > 4) {
      that.setData({
        scrollLeft: 300
      })
    } else {
      that.setData({
        scrollLeft: 0
      })
    }
  },
  //头部导航点击
  swichNav: function(e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current,
        showmap: true,
        showlist: false
      })
    }
  },
  moveToLocation: function() {
    this.mapCtx.moveToLocation()
  },
  //上拉加载
  onReachBottom: function() {
    var that = this
    var companyid = that.data.companyid
    that.setData({
      page: that.data.page + 1 //后台数据需要分页，每次加载一页
    })
    wx.showLoading({ //显示toast
      title: '加载中...',
    });
    var page = that.data.page
    //page = page + 1;
    wx.request({
      url: app.apiUrl('c=buildingsite/index&a=getlist&company'),
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        company_id: companyid,
        page: that.data.page
      },
      method: 'GET',
      success: function(res) {
        console.log(res.data.datas)
        if (res.data.code == 200) {
          var listdata = that.data.polist
          var locals = that.data.local
          for (var i = 0; i < res.data.datas.list.length; i++) {
            listdata.push(res.data.datas.list[i]);
            var local = listdata[i].location
            if (local == null) {
              local = '0,0'
            } else {
              local = listdata[i].location
            }
            var strArray = local.split(",");
            locals.push(strArray)
          }
          that.setData({
            polist: listdata,
            local:locals
          });
        } else if (res.data.code == 400) {
          wx.showLoading({
            title: '加载完毕',
          })
        }
        console.log(page)
        setTimeout(function(){
          that.getlocal();
          that.distance();
        },200)
      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
        wx.hideNavigationBarLoading() //完成停止加载
        wx.hideLoading(); //隐藏toast
        // setTimeout(function() {
        //   wx.showToast({
        //     title: '没有更多数据了！',
        //   })
        // }, 2000)
      }
    })
  },
  //下拉刷新
  onPullDownRefresh: function() {
    var that = this
    var page = that.data.page
    var companyid = that.data.companyid
    wx.request({
      url: app.apiUrl('c=buildingsite/index&a=getlist&company'),
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        company_id: companyid,
        //page: page,
      },
      success: function(res) {
        var polist = res.data.datas.list
        var arr1 = []
        for (var i in polist) {
          var local = polist[i].location
          if (local == null) {
            local = '0,0'
          } else {
            local = polist[i].location
          }
          var strArray = local.split(","); 
          arr1.push(strArray)
        }
        that.setData({
          polist: polist,
          local: arr1
        })
        setTimeout(function () {
          that.getlocal();
          that.distance();
        }, 200)
      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
        setTimeout(function() {
          wx.hideLoading()
        }, 2000)
        wx.stopPullDownRefresh() //停止下拉刷新
      }
    })
  },
 //到工地详情页面
  skipTolivedetail:function(e){
    var ids = parseInt(e.currentTarget.id) 
    var polist = this.data.polist[ids]
    var picid = e.currentTarget.dataset.albuid
    // if ((polist.distance == 12843) || (polist.distance == 12851)){
    //   this.setData({
    //     distance:0,
    //     mapcount: polist,
    //     state: false,
    //   })
    // }else{
    //   this.setData({
    //     distance: polist.distance,
    //     mapcount: polist,
    //     state: true
    //   })
    // }  
    wx.navigateTo({
      url: 'livesite_detail?picid='+picid,
    })
  },

  appointment: function () {
    this.setData({
      showinfo: true,
      mask: true,
      hidemap: true,
      showimg: false
    })
  },
  hidemask: function () {
    this.setData({
      showinfo: false,
      mask: false,
      hidemap: false,
      showimg: true
    })
  },
  //输入号码时，预约输入判断
  bindKeyInput: function (e) {
    var value = e.detail.value
    var info = 1
    this.setData({
      info: info,
      hidecode: false,
      showcode: true,
      infotele: value
    })
  },
  settime: function () {
    var that = this
    setTimeout(function () {
      that.setData({
        alertmess: false
      })
    }, 2000)
  },
  //获取验证码
  getCode: function (e) {
    var that = this
    var text = '获取验证码'
    var tele = that.data.infotele
    var card = that.data.card
    var sid = that.data.sid
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (tele == '') {
      that.setData({
        alertmess: true,
        message: '请输入手机号码！'
      })
      that.settime()
    } else if (tele.length != 11) {
      that.setData({
        alertmess: true,
        message: '请重新输入手机号码！'
      })
      that.settime()
    } else if (!myreg.test(tele)) {
      that.setData({
        alertmess: true,
        message: '手机号错误，请重新输入！'
      })
      that.settime()
    } else {
      wx.request({
        url: app.apiUrl('c=zhaobiao/index&a=get_captcha'),
        data: {},
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Cookie': 'PHPSESSID=' + sid
        },
        method: "GET",
        success: function (res) {
          console.log(res.data)
          var cards = res.data.datas.code
          //var landing_page = res.data.datas.landing_page
          console.log(cards)
          that.setData({
            card: cards,
            distate: false
          })
          setTimeout(function () {
            that.setData({
              card: text,
              distate: false
            })
          }, 60000)
        },
        fail: function (res) {
          console.log('请求失败', res.data)
        }
      })
    }
  },
  formSubmit: function (e) {
    var that = this
    var mobile = e.detail.value.mobile
    var code = e.detail.value.code
    var id = that.data.tid
    var thecode = that.data.card
    var sid = that.data.sid
    var basepeak = that.data.basepeak
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    console.log('提交', sid)
    console.log(thecode)
    var id = 1
    var title = '预约成功'
    var tsmall = '"恭喜您，预约成功，我们将尽快与您联系!'
    if (mobile == '') {
      that.setData({
        alertmess: true,
        message: '手机号码不能为空！'
      })
      that.settime()
    } else if (mobile.length != 11) {
      that.setData({
        alertmess: true,
        message: '请重新输入手机号码！'
      })
      that.settime()
    } else if (!myreg.test(mobile)) {
      that.setData({
        alertmess: true,
        message: '手机号错误，请重新输入！'
      })
      that.settime()
    } else if (code == '') {
      that.setData({
        alertmess: true,
        message: '验证码不能为空！'
      })
      that.settime()
    } else if (code != thecode) {
      that.setData({
        alertmess: true,
        message: '验证码不对，请重新输入！'
      })
      that.settime()
    } else {
      wx.request({
        url: app.apiUrl('c=zhaobiao/index&a=submit_visit'),
        data: {
          phone: mobile,
          code: code,
          company_id: id,
          landing_page: basepeak
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Cookie': 'PHPSESSID=' + sid
        },
        method: "POST",
        success: function (res) {
          console.log(res.data)
          var code = res.data.code
          var message = res.data.error
          if (code == 200) {
            wx.navigateTo({
              url: '../free/applysuccess?data=' + [id, title, tsmall],
            })
            that.setData({
              showinfo: false,
              mask: false,
              hidemap: false,
              showimg: true
            })
          } else {
            that.setData({
              alertmess: true,
              message: message
            })
            that.settime()
          }
        },
        fail: function (res) {
          console.log('请求失败', res.data)
        }
      })
      this.setData({
        showModal: false,
        Modalcontent: false,
        showinfo: false,
        mask: false
      })
    }
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
  }

})